var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    maintenance_date:moment().format('YYYY-MM-DD'),
    imgList:[],
    formType : 'add',
    pageType:'cm',
    isAdd:true,
    type:true
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": "车辆档案" });
    var that = this;
    //更新数据
    that.setData({
      vehicle_id: e.id,
      tab: e.tab || 3,
      role_default:app.globalData.role_default,
      server:app.server
    });
    this.loadData();
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  changePagetype: function (e) {
    var that = this;
    this.setData({
      pageType:e.currentTarget.dataset.type
    })
    if(e.currentTarget.dataset.type == 'cmrecords'){
      that.loadRechargeData()
    }
    if(e.currentTarget.dataset.type == 'cm'){
      that.loadData()
    }
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.getData("/atapi/vehicle/vehicle/cold_machine", {
      'CO_ID': app.globalData.CO_ID,
      vehicle: that.data.vehicle_id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize
    }, function (res, error) {
      console.log(res); console.log(error)
      setTimeout(function(){
        wx.hideLoading();
      },100);
      if (res.data.success) {
        wx.setNavigationBarTitle({ "title": "冷机--" + res.data.data[0][0].plate });
        var dataList = res.data.data[1];
        for(var i=0;i<dataList.length;i++){
          if(dataList[i].maintenance_expire){
            dataList[i].maintenance_expire_day = moment(dataList[i].maintenance_expire).fromNow('d')
          }
        }
        that.setData({
          plate:res.data.data[0][0].plate,
          d_user_id:res.data.data[0][0].d_user_id,
          user_id:app.globalData.user_id,
          driverName:res.data.data[0][0].name,
          is_fleet:app.globalData.role_default == 'fleet'?true:false,
          dataList: dataList,
          isAdd:res.data.data[1].length > 1?false:true
        });
      } else {
        that.setData({
          dataList: []
        });
      }
    });
  },
  loadRechargeData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.getData("/atapi/vehicle/vehicle/cold_machine_records", {
      'CO_ID': app.globalData.CO_ID,
      vehicle: that.data.vehicle_id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize
    }, function (res, error) {
      console.log(res); console.log(error)
      setTimeout(function(){
        wx.hideLoading();
      },100);
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          recordsList: res.data.data[0],
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          recordsList: []
        });
      }
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.title,
      modalType:e.currentTarget.dataset.type,
      formType:e.currentTarget.dataset.type
    })
    if(e.currentTarget.dataset.type == 'edit' && e.currentTarget.dataset.target == 'detailModal'){
       var id = e.currentTarget.id;
       var dataList = that.data.dataList;
       for(var i=0;i<dataList.length;i++){
         if(dataList[i].ID == id){
            that.setData({
              id:dataList[i].ID,
              type:dataList[i].type == '大冷机'?true:false,
              brand:dataList[i].brand
            })
         }
       }
    }
    if(e.currentTarget.dataset.target == 'recordsModal' && that.data.dataList.length == 0){
      wx.showToast({
        title: "请先添加冷机",
        image: '/images/wrong.png',
        duration: 2000
      });
      this.setData({
        modalName: null
      })
    }
    if(e.currentTarget.dataset.target == 'recordsModal' && e.currentTarget.dataset.type == 'detail'){
      var id = e.currentTarget.id;
      var recordsList = that.data.recordsList;
      for(var i=0;i<recordsList.length;i++){
        if(recordsList[i].ID == id){
          var currentData = [];
          currentData.push({name:'冷机类型',value:recordsList[i].type});
          currentData.push({name:'保养日期',value:recordsList[i].maintenance_date});
          currentData.push({name:'保养费用',value:recordsList[i].fee});
          currentData.push({name:'保养人',value:recordsList[i].ADD_USER_NAME});
           that.setData({
             _currentData:recordsList[i],
              currentData:currentData
           })
        }
      }
   }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  showPictrue: function (e) {
    var image = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: image
    })
  },
  previewImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var current = e.currentTarget.dataset.url
    var imgList = that.data.imgList;
    wx.previewImage({
      current: current,
      urls: imgList
    })
  },
  chooseImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var imgList = that.data.imgList;
    try{
      var formData = {
        'id': that.data.vehicle_id,
        'type':'maintenance'
      };
    }catch(e){}
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/atapi/vehicle/vehicle/uploadImage',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                imgList.push(data.data);
                imgList = util.arrayDeleteEmpty(imgList);
                that.setData({
                  imgList: imgList
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.imgList;
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if(url == ''){
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      that.setData({
        imgList: imgList
      })
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/vehicle/vehicle/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index,1);
        }
        that.setData({
          imgList: imgList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        });
      }
    });
  },
  //提交表单
  saveFormData: function () {
    var that = this;

    var formData = {};

    formData.type = that.data.type?'大冷机':'小冷机';
    formData.brand = that.data.brand||'';
    formData.maintenance_day = that.data.maintenance_day||'';
    console.log(formData)
    var dataList = that.data.dataList;

    if (formData.type == '') {
      wx.showToast({
        title: "请选择冷机类型",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    
    var type = '';
    if(dataList.length > 0){
      type = dataList[0].type;
      if(formData.type == type){
        wx.showToast({
          title: "已有："+type,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
    }

    if (formData.brand == '') {
      wx.showToast({
        title: "请填写冷机品牌",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.maintenance_day == '') {
      wx.showToast({
        title: "请填写保养周期",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;
    formData.vehicle = that.data.vehicle_id;
    formData.plate = that.data.plate;
    if (that.data.formType == 'add'){
      util.postData("/atapi/vehicle/vehicle/cold_machine", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }else{
      formData.id = that.data.id;
      util.putData("/atapi/vehicle/vehicle/cold_machine", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "编辑成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "编辑失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
    
  },
  deleteData:function(){
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
          util.deleteData("/atapi/vehicle/vehicle/cold_machine", {
            id: that.data.id,
            plate: that.data.plate,
            type: (that.data.type?'大冷机':'小冷机'),
            user_id:app.globalData.user_id,
            CO_ID:app.globalData.CO_ID,
            truename:app.globalData.truename,
            logs:that.data.card+','+that.data.brand+','+(that.data.type?'大冷机':'小冷机')+','+app.globalData.user_id+','+app.globalData.truename
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {
                  setTimeout(function(){
                    that.hideModal();
                      that.loadData();
                  },3000)
                }
              });
            }
          });
        }
      }
      })
  },
  //提交表单
  saveRecordsFormData: function () {
    var that = this;

    var formData = {};

    formData.fee = that.data.fee||'';
    formData.maintenance_date = that.data.maintenance_date||'';
    console.log(formData)
    if (formData.fee == '') {
      wx.showToast({
        title: "请填写费用",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.fee)) {
      wx.showToast({
        title: "费用错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;
    formData.ADD_USER_NAME = app.globalData.truename;
    formData.vehicle = that.data.vehicle_id;
    formData.plate = that.data.plate;

    var dataList = that.data.dataList;
    for(var i=0;i<dataList.length;i++){
      var _type = dataList[i].type == '大冷机'?true:false;
       if(_type == that.data.type){
          formData.type = dataList[i].type;
          formData.cm = dataList[i].ID;
          formData.maintenance_day = dataList[i].maintenance_day;
       }
    }

    util.postData("/atapi/vehicle/vehicle/cold_machine_records", formData, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading()
      if (res.data.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.hideModal();
              that.loadRechargeData();
              that.setData({
                amount:''
              })
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title: "提交失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
    
  },
  deleteRecordsData:function(){
    var that = this;
    var dataList = that.data.dataList,_datalist = {};
    for(var i=0;i<dataList.length;i++){
      var _type = dataList[i].type == '大冷机'?true:false;
       if(_type == that.data.type){
          _datalist = dataList[i];
       }
    }

    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
          util.deleteData("/atapi/vehicle/vehicle/cold_machine_records", {
            id: that.data._currentData.ID,
            user_id:app.globalData.user_id,
            CO_ID:app.globalData.CO_ID,
            truename:app.globalData.truename,
            logs:_datalist.fee+','+_datalist.maintenance_date+','+app.globalData.user_id+','+app.globalData.truename
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {
                  setTimeout(function(){
                    that.hideModal();
                      that.loadRechargeData();
                  },3000)
                }
              });
            }
          });
        }
      }
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})